
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
/**
 * The Cryptography class uses AES encryption to encrypt and decrypt strings
 * @author Owen Cox
 */
public class Cryptography {
	static Cipher Encipher;
	static Cipher Decipher;
	/**
	 * Initializes the cypher.
	 */
	public static void init(){
		try{
			byte[] raw = {68, 4, -86, -17, -116, 49, -1, 32, 
					-119, 53, -45, -61, -69, -42, -39, -89};
			SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			Decipher = Cipher.getInstance("AES");
			Encipher = Cipher.getInstance("AES");
			Encipher.init(Cipher.ENCRYPT_MODE, skeySpec);
			Decipher.init(Cipher.DECRYPT_MODE, skeySpec);
		}
		catch(Exception e){
			System.out.println("Cryptography failed to load.");
			Logger.log("Cryptography failed to load.");
		}
	}
	/**
	 * @param s
	 * @return the encrypted string
	 */
	public static String encrypt(String s){
		return byteToString(encryptToBytes(s));
	}
	/**
	 * @param s
	 * @return the decrypted string
	 */
	public static String decrypt(String s){
		return decryptBytes(stringToByte(s));
	}
	/**
	 * @param s
	 * @return the encrypted bytes
	 */
	public static byte[] encryptToBytes(String s){
		if (Encipher==null){
			init();
		}
		try{
			return Encipher.doFinal(s.getBytes());
		}
		catch(Exception e){
			return s.getBytes();
		}
	}
	/**
	 * @param s
	 * @return the decrypted bytes, in string form
	 */
	public static String decryptBytes(byte[] s){
		if (Decipher==null){
			init();
		}
		try{
			return new String(Decipher.doFinal(s));
		}
		catch(Exception e){
			return new String(s);
		}
	}
	/**
	 * @param arr
	 * @return A string made up of the byte array
	 */
	private static String byteToString(byte[] arr){
		String s="";
		for (byte b:arr){
			s+=(char)b;
		}
		return s;
	}
	/**
	 * @param s
	 * @return the bytes that compose the string
	 */
	private static byte[] stringToByte(String s){
		char[] c=s.toCharArray();
		byte[] b= new byte[c.length]; 
		for (int i=0; i<c.length; i++){
			b[i]=(byte) c[i];
		}
		return b;
	}
}

